<?php declare(strict_types=1);

$resource = $_GET['method'];

$token = '';

if (isset($_SERVER['HTTP_ACCESS_TOKEN'])) {
    $token = $_SERVER['HTTP_ACCESS_TOKEN'];
} elseif (isset($_SERVER['HTTP_AUTHORIZATION'])) {
    $token = $_SERVER['HTTP_AUTHORIZATION'];
} elseif (isset($_COOKIE['token'])) {
    $token = $_COOKIE['token'];
} else {
    $token = isset($_GET['token']) ? $_GET['token'] : '';
}

$di = \application\units\Di::getInstance();

$router = $di->router[$resource];

if (!is_array($router)) {
    $router = [
        'path'       => $router,
        'permission' => 'permission',
    ];
}

// 初始化登录用户
$isLogin = $di->auth->init($token);

if ($isLogin === false) {
    if ($router['permission'] === 'public') {
        return true;
    } else {
        throw new \LogicException('登录状态失效', 20001);
    }
}

if ($di->auth->status != 1) throw new \LogicException('账号已禁用', 10002);

if ($router['permission'] === 'allow' || $router['permission'] === 'public') {
    // 设置白名单资源
    $di->auth->setAllowResources([
        $resource,
    ]);
}

// 判断资源权限
if ($di->auth->permission($resource) === false) throw new LogicException('没有权限操作', 99999);

if ($di->request->isPost()) {
    $di->auth->log([
        'admin_id'    => $di->auth->id,
        'username'    => $di->auth->username,
        'url'         => $di->request->server('HTTP_REFERER'),
        'title'       => $resource,
        'content'     => json_encode($di->request->params(), JSON_UNESCAPED_UNICODE),
        'ip'          => $di->request->ip(),
        'useragent'   => $di->request->server('HTTP_USER_AGENT'),
        'create_time' => date('Y-m-d H:i:s'),
    ]);
}